<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>书籍购物车</title>
  <link href="../../css/vue.css" type="text/css" rel="stylesheet">
</head>
<body>
<div id="app">
  <table class="gridTable">
    <thead>
    <tr>
      <th>书籍名称</th>
      <th>出版日期</th>
      <th>价格</th>
      <th>购买数量</th>
      <th>操作</th>
    </tr>
    </thead>
    <tbody>
    <tr v-for="(book,index) in books" v-if="bookSize > 0">
      <td>{{book.name}}</td>
      <td>{{book.date}}</td>
      <td>{{book.price | showPrice}}</td>
      <td>
        <button @click="subItem(book,index)">-</button>
        {{book.count}}
        <button @click="addItem(book,index)">+</button>
      </td>
      <td>
        <button @click="deleteItem(book,index)">移除</button>
      </td>
    </tr>
    <tr v-show="bookSize <=0">
      <td colspan="5">
        当前没有数据
      </td>
    </tr>
    </tbody>
    <tfoot>
    <tr>
      <td colspan="5">总价：{{allPrice}}</td>
    </tr>
    </tfoot>
  </table>
</div>

<script src="../../js/vue.js"></script>
<script>
  const app = new Vue({
    el: "#app",
    data: {
      books: [{id: 1, name: "算法导论", date: '2019-01', price: 98, count: 1}
        , {id: 2, name: "算法导论1", date: '2019-02', price: 99, count: 1}
        , {id: 3, name: "算法导论2", date: '2019-03', price: 100, count: 1}
        , {id: 4, name: "算法导论3", date: '2019-04', price: 101, count: 1}
        , {id: 5, name: "算法导论4", date: '2019-05', price: 102, count: 1}
      ],
    },
    computed: {
      allPrice: function () {
        let allPrice = 0;
        //js增强循环
        this.books.forEach(function (value) {
          allPrice += value.price * value.count
        })
        /*
          //es6循环方式1
          for(let index in this.books){
            allPrice += this.books[index].price * this.books[index].count
          }
          //es6循环方式2
          for(let item of this.books){
            allPrice += item.price * item.count
          }
        */
        return allPrice;
      },
      bookSize() {
        console.log("计算size")
        return this.books.length
      }
    },
    //■过滤器，会将 book.price | showPrice 中的book.price传入showPrice这个过滤器，然后返回我们拼接的字符串
    filters: {
      showPrice(price) {
        return "￥" + price.toFixed(2)
      }
    },
    methods: {
      deleteItem(book, index) {
        console.log(index)
        this.books.splice(index, 1)
      },
      subItem(book, index) {
        if (book.count > 0) {
          book.count -= 1;
          this.books[index].count = book.count;
          return book.count;
        }
      },
      addItem(book, index) {
        book.count += 1;
        this.books[index].count = book.count;
        return book.count;
      }
    }
  });
</script>
</body>
</html>